/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.utils;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2016/1/27
 */
public class RandomDigitsGenerator {

    private static final String NUMERAL_10 = "0123456789";

    /**
     * 针对长度参数的非法参数错误提示
     */
    private static final String ILLEGAL_ARGUMENT_MESSAGE = "Length must be positive";

    /**
     * 字符串长度默认值
     */
    private static final int DEFAULT_LENGTH = 4;

    /**
     * 字符串长度
     */
    private int length = DEFAULT_LENGTH;

    /**
     * 可以指定字符串前缀
     */
    private String prefix;

    /**
     * 默认构造方法
     * <ol>
     * <li>length 4</li>
     * <li>prefix none</li>
     * </ol>
     */
    public RandomDigitsGenerator() {
    }

    /**
     * 指定数字串长度构造方法
     * <ol>
     * <li>length as provided</li>
     * <li>prefix none</li>
     * </ol>
     *
     * @param length 数字串长度
     */
    public RandomDigitsGenerator(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
        }
        this.length = length;
    }

    /**
     * 指定字符串前缀构造方法
     * <ol>
     * <li>length 4</li>
     * <li>prefix as provided</li>
     * <ol>
     *
     * @param prefix 指定字符串前缀
     */
    public RandomDigitsGenerator(String prefix) {
        this.prefix = prefix;
    }

    /**
     * 指定数字串长度及字符串前缀构造方法
     * <ol>
     * <li>length as provided</li>
     * <li>prefix as provided</li>
     * <ol>
     *
     * @param length 字符串长度
     * @param prefix 指定字符串前缀
     */
    public RandomDigitsGenerator(int length, String prefix) {
        if (length <= 0) {
            throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
        }
        this.length = length;
        this.prefix = prefix;
    }

    /**
     * 获得随机数字串
     *
     * @return 随机数字串
     */
    public String random() {
        StringBuilder sb = new StringBuilder(this.length);
        if (prefix != null && !("").equals(prefix.trim())) {
            sb.append(prefix);
        }
        for (int i = 0; i < this.length; i++) {
            sb.append(NUMERAL_10.charAt(ThreadLocalRandom.current().nextInt(NUMERAL_10.length())));
        }
        return sb.toString();
    }
}
